package com.xz.knowledgeDuplication.pattern.singleton;

/**
 * 懒汉式: 双重检查锁
 *
 * @author 召
 * @date 2022-02-17 20:38:56
 */
public class Singleton04 {

    private Singleton04() {}

    // volatile 关键字可以保证可见性和有序性。
    private static volatile Singleton04 instance;

    public static Singleton04 getInstance() {
        // 第一次判断,如果instance的值不为null,不需要抢占锁直接返回对象
        if (instance == null) {
            synchronized (Singleton04.class) {
                if (instance == null) {
                    instance = new Singleton04();
                }
            }
        }
        return instance;
    }
}
